from flask import Blueprint, render_template, redirect, url_for, flash, request, session
from app import db
from app.models.user import User
from app.models.role import Role
from app.models.menu import Menu
from app.routes.auth import login_required

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')

@admin_bp.route('/')
@login_required
def index():
    # 获取统计数据
    user_count = User.query.count()
    role_count = Role.query.count()
    menu_count = Menu.query.count()
    return render_template('admin/index.html', user_count=user_count, role_count=role_count, menu_count=menu_count)

# 用户管理
@admin_bp.route('/users')
@login_required
def user_list():
    users = User.query.all()
    roles = Role.query.all()
    return render_template('admin/user/list.html', users=users, roles=roles)

@admin_bp.route('/users/data')
@login_required
def user_data():
    users = User.query.all()
    data = []
    for user in users:
        role = Role.query.get(user.role_id)
        data.append({
            'id': user.id,
            'username': user.username,
            'role_name': role.name if role else '',
            'created_at': user.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': user.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return {'code': 0, 'msg': '', 'count': len(data), 'data': data}

@admin_bp.route('/users/add', methods=['GET', 'POST'])
@login_required
def user_add():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        role_id = request.form['role_id']

        existing_user = User.query.filter_by(username=username).first()
        if existing_user:
            return {'success': False, 'msg': '用户名已存在！'}

        new_user = User(username=username, password=password, role_id=role_id)
        db.session.add(new_user)
        db.session.commit()

        return {'success': True, 'msg': '用户添加成功！'}
    roles = Role.query.all()
    return render_template('admin/user/list.html', roles=roles)

@admin_bp.route('/users/edit/<int:user_id>', methods=['GET', 'POST'])
@login_required
def user_edit(user_id):
    user = User.query.get_or_404(user_id)
    if request.method == 'POST':
        user.username = request.form['username']
        if request.form.get('password'):
            user.password = request.form.get('password')
        user.role_id = request.form['role_id']

        db.session.commit()
        return {'success': True, 'msg': '用户编辑成功！'}
    roles = Role.query.all()
    return render_template('admin/user/list.html', user=user, roles=roles)

@admin_bp.route('/users/delete/<int:user_id>', methods=['GET', 'POST'])
@login_required
def user_delete(user_id):
    user = User.query.get_or_404(user_id)
    db.session.delete(user)
    db.session.commit()
    if request.method == 'POST':
        return {'success': True, 'msg': '用户删除成功！'}
    else:
        flash('用户删除成功！', 'success')
        return redirect(url_for('admin.user_list'))

# 菜单管理
@admin_bp.route('/menus')
@login_required
def menu_list():
    menus = Menu.query.order_by(Menu.parent_id, Menu.order).all()
    parent_menus = Menu.query.filter_by(parent_id=None).all()  # 获取所有一级菜单
    return render_template('admin/menu/list.html', menus=menus, parent_menus=parent_menus)

@admin_bp.route('/menus/add', methods=['GET', 'POST'])
@login_required
def menu_add():
    if request.method == 'POST':
        name = request.form['name']
        url = request.form['url']
        icon = request.form.get('icon')  # 使用get方法避免KeyError
        parent_id = request.form.get('parent_id') or None  # 更安全的方式处理可选字段
        order = request.form.get('order')  # 使用get方法避免KeyError

        new_menu = Menu(name=name, url=url, icon=icon, parent_id=parent_id, order=order)
        db.session.add(new_menu)
        db.session.commit()

        return {'success': True, 'msg': '菜单添加成功！'}
    parent_menus = Menu.query.filter_by(parent_id=None).all()
    return render_template('admin/menu/list.html', parent_menus=parent_menus)

@admin_bp.route('/menus/edit/<int:menu_id>', methods=['GET', 'POST'])
@login_required
def menu_edit(menu_id):
    menu = Menu.query.get_or_404(menu_id)
    if request.method == 'POST':
        menu.name = request.form['name']
        menu.url = request.form['url']
        menu.icon = request.form.get('icon')  # 使用get方法避免KeyError
        menu.parent_id = request.form.get('parent_id') or None  # 更安全的方式处理可选字段
        menu.order = request.form.get('order')  # 使用get方法避免KeyError

        db.session.commit()
        return {'success': True, 'msg': '菜单编辑成功！'}
    parent_menus = Menu.query.filter_by(parent_id=None).all()
    return render_template('admin/menu/list.html', menu=menu, parent_menus=parent_menus)

@admin_bp.route('/menus/delete/<int:menu_id>', methods=['GET', 'POST'])
@login_required
def menu_delete(menu_id):
    menu = Menu.query.get_or_404(menu_id)
    # 检查是否有子菜单
    children = Menu.query.filter_by(parent_id=menu_id).all()
    if children:
        if request.method == 'POST':
            return {'success': False, 'msg': '请先删除子菜单！'}
        else:
            flash('请先删除子菜单！', 'error')
            return redirect(url_for('admin.menu_list'))
    db.session.delete(menu)
    db.session.commit()
    if request.method == 'POST':
        return {'success': True, 'msg': '菜单删除成功！'}
    else:
        flash('菜单删除成功！', 'success')
        return redirect(url_for('admin.menu_list'))

# 角色管理
@admin_bp.route('/roles/data')
@login_required
def role_data():
    roles = Role.query.all()
    data = []
    for role in roles:
        data.append({
            'id': role.id,
            'name': role.name,
            'description': role.description,
            'created_at': role.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': role.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return {'code': 0, 'msg': '', 'count': len(data), 'data': data}

@admin_bp.route('/roles')
@login_required
def role_list():
    roles = Role.query.all()
    return render_template('admin/role/list.html', roles=roles)

@admin_bp.route('/roles/add', methods=['GET', 'POST'])
@login_required
def role_add():
    if request.method == 'POST':
        name = request.form['name']
        description = request.form.get('description', '')  # 使用get方法避免KeyError

        existing_role = Role.query.filter_by(name=name).first()
        if existing_role:
            return {'success': False, 'msg': '角色名称已存在！'}

        new_role = Role(name=name, description=description)
        db.session.add(new_role)
        db.session.commit()

        return {'success': True, 'msg': '角色添加成功！'}
    return render_template('admin/role/list.html')

@admin_bp.route('/roles/edit/<int:role_id>', methods=['GET', 'POST'])
@login_required
def role_edit(role_id):
    role = Role.query.get_or_404(role_id)
    if request.method == 'POST':
        role.name = request.form['name']
        role.description = request.form.get('description', '')  # 使用get方法避免KeyError

        db.session.commit()
        return {'success': True, 'msg': '角色编辑成功！'}
    return render_template('admin/role/list.html', role=role)

@admin_bp.route('/roles/delete/<int:role_id>', methods=['GET', 'POST'])
@login_required
def role_delete(role_id):
    role = Role.query.get_or_404(role_id)
    # 检查是否有用户关联此角色
    users = User.query.filter_by(role_id=role_id).all()
    if users:
        if request.method == 'POST':
            return {'success': False, 'msg': '请先删除关联此角色的用户！'}
        else:
            flash('请先删除关联此角色的用户！', 'error')
            return redirect(url_for('admin.role_list'))
    db.session.delete(role)
    db.session.commit()
    if request.method == 'POST':
        return {'success': True, 'msg': '角色删除成功！'}
    else:
        flash('角色删除成功！', 'success')
        return redirect(url_for('admin.role_list'))

# 角色菜单管理
@admin_bp.route('/roles/menus/<int:role_id>')
@login_required
def role_menus(role_id):
    role = Role.query.get_or_404(role_id)
    menus = Menu.query.order_by(Menu.parent_id, Menu.order).all()
    role_menus = []
    for menu in menus:
        role_menus.append({
            'id': menu.id,
            'name': menu.name,
            'url': menu.url,
            'has': menu in role.menus
        })
    return {'success': True, 'menus': role_menus}

@admin_bp.route('/roles/add_menu', methods=['POST'])
@login_required
def add_role_menu():
    role_id = request.form['role_id']
    menu_id = request.form['menu_id']
    role = Role.query.get_or_404(role_id)
    menu = Menu.query.get_or_404(menu_id)
    if menu not in role.menus:
        role.menus.append(menu)
        db.session.commit()
        return {'success': True, 'msg': '菜单分配成功！'}
    return {'success': False, 'msg': '菜单已经分配给该角色！'}

@admin_bp.route('/roles/remove_menu', methods=['POST'])
@login_required
def remove_role_menu():
    role_id = request.form['role_id']
    menu_id = request.form['menu_id']
    role = Role.query.get_or_404(role_id)
    menu = Menu.query.get_or_404(menu_id)
    if menu in role.menus:
        role.menus.remove(menu)
        db.session.commit()
        return {'success': True, 'msg': '菜单移除成功！'}
    return {'success': False, 'msg': '菜单未分配给该角色！'}